<template>
  <div class="w-full">
    <Upload
      draggable
      action="/"
      :show-file-list="false"
      v-bind="extendProps"
      v-model="uploadRes"
      v-model:file-list="fileList"
      v-model:show="show"
      @uploaded="emits('uploaded')"
      :fileNameKey="fileNameKey"
      :filePathKey="filePathKey"
      @fileList="handle"
    >
      <template #tips>
        <slot />
      </template>
    </Upload>
    <slot name="description"></slot>
    <span class="file-list" v-if="show">
      <template v-for="(item, index) in fileList" :key="item[props.filePathKey]">
        <a-link class="text-[#465A80_!important]">
          {{ item[props.fileNameKey] }}
          <icon-delete class="cursor-pointer ml-2" @click="removeThis(index)"
        /></a-link>
      </template>
    </span>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, type PropType } from 'vue';
import Upload from './FileMultiUpload.vue';
const handle = (val) => {
  if (props.extendProps.single) {
    fileList.value = val;
  } else {
    fileList.value.push(...val);
  }
};
const props = defineProps({
  extendProps: {
    type: Object as PropType<Record<string, any>>,
    default: () => ({})
  },
  modelValue: {
    type: String,
    default: ''
  },
  fileList: {
    type: Array as PropType<Record<string, any>[]>,
    default: () => []
  },
  fileNameKey: {
    type: String,
    default: 'fileName'
  },
  filePathKey: {
    type: String,
    default: 'url'
  },
  show: {
    type: Boolean,
    default: true
  }
});
const emits = defineEmits(['update:modelValue', 'input', 'uploaded']);
const uploadRes = ref(props.modelValue);
const fileList = ref(props.fileList);
const show = ref(props.show);
function removeThis(index: number) {
  // 是否是单文件上传
  if (props.extendProps.single) {
    // emits('update:modelValue', '');
    emits('input', '');
    fileList.value = [];
  } else {
    const res = props.modelValue.split(',');
    res.splice(index, 1);
    emits('input', res.join(','));
    fileList.value.splice(index, 1);
    if (fileList.value.length <= 0) {
      show.value = false;
    }
  }
}
watch(
  uploadRes,
  (val) => {
    // 高配版
    emits('update:modelValue', val);
    // 平民版
    emits('uploaded', val);
  },
  {
    deep: true
  }
);
</script>

<style lang="less" scoped></style>
